<template>
	<view class="img-container">
		<view class="image-list">
			<view class="image-item" v-for="(image, index) in tempImages" :key="index">
				<image :src="image.path" class="preview-image" mode="aspectFill" />
				<view class="delete-btn" @click="removeImage(index)">×</view>
			</view>
			<view class="add-image" v-if="tempImages.length < 3" @click="chooseImage">
				<uni-icons type="plusempty" size="30" color="#999"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	defineProps,
	defineEmits
} from 'vue';

const props = defineProps({
	// 默认头像
	defaultImg: {
		type: String,
		default: '/static/default-avatar.png'
	},
	// 当前头像URL
	currentImg: {
		type: String,
		default: ''
	},
	// 是否显示上传文字提示
	showUploadText: {
		type: Boolean,
		default: true
	}
});

const emit = defineEmits(['imagesReady']);

// 临时存储选择的图片
const tempImages = ref([]);

// 选择图片
const chooseImage = async () => {
	try {
		const res = await uni.chooseImage({
			count: 3 - tempImages.value.length, // 最多还能选几张
			sizeType: ['compressed'], // 压缩图片
			sourceType: ['album', 'camera'] // 可以从相册选择或使用相机
		});

		if (res.tempFilePaths) {
			// 添加新选择的图片到临时数组
			const newImages = res.tempFilePaths.map(path => ({
				path,
				uploaded: false
			}));
			tempImages.value = [...tempImages.value, ...newImages];
		}
	} catch (err) {
		console.error('选择图片失败:', err);
		uni.showToast({
			title: '选择图片失败',
			icon: 'none'
		});
	}
};

// 删除选择的图片
const removeImage = (index) => {
	tempImages.value.splice(index, 1);
};

// 上传所有图片
const uploadImages = async () => {
	if (tempImages.value.length === 0) {
		return [];
	}

	try {
		uni.showLoading({ title: '上传中...' });

		const uploadPromises = tempImages.value.map(async (image) => {
			if (image.uploaded) {
				return image.fileID; // 如果已经上传过，直接返回fileID
			}

			const result = await uniCloud.uploadFile({
				filePath: image.path,
				cloudPath: `blog-images/${Date.now()}-${Math.random().toString(36).slice(-6)}.jpg`
			});

			return result.fileID;
		});

		const fileIDs = await Promise.all(uploadPromises);
		uni.hideLoading();
		return fileIDs;

	} catch (err) {
		uni.hideLoading();
		console.error('上传图片失败:', err);
		throw err;
	}
};

// 暴露上传方法给父组件
defineExpose({
	uploadImages,
	clearImages: () => {
		tempImages.value = [];
	}
});
</script>

<style lang="scss" scoped>
.img-container {
	width: 100%;
	padding: 20rpx;
	box-sizing: border-box;

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;

		.image-item {
			position: relative;
			width: 200rpx;
			height: 200rpx;

			.preview-image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
				object-fit: cover;
			}

			.delete-btn {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				width: 40rpx;
				height: 40rpx;
				line-height: 36rpx;
				text-align: center;
				background-color: rgba(0, 0, 0, 0.5);
				color: #fff;
				border-radius: 50%;
				font-size: 32rpx;
			}
		}

		.add-image {
			width: 200rpx;
			height: 200rpx;
			border: 2rpx dashed #999;
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #f5f5f5;

			&:active {
				background-color: #e5e5e5;
			}
		}
	}
}
</style>